var $yd = {
    isForbidCutKey : 0
};
$yd.isEmpty = function(value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
// 校验手机号
$yd.validateTel = function (tel) {
    var myreg=/^[1][0-9][0-9]{9}$/;
    if (!myreg.test(tel)) {
        return false;
    } else {
        return true;
    }
}
$.extend($.fn.validatebox.defaults.rules, {
    equals: {
        validator: function(value,param){
            return value == $(param).val();
        },
        message: '两次密码输入不一致'
    },
    pwdValidate: {
        validator: function(value, param){
            // 验证密码 6-12位数字加字母
            var reg =new RegExp(param);
            // var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
            return reg.test(value);
        },
        message: "要求密码是 6-12位数字加字母!"
    },
    telValidate: {
        validator: function(value, param){
            var reg=/^[1][0-9][0-9]{9}$/;
            return reg.test(value);
        },
        message: "手机号格式不正确（要求11位数字手机号）"
    }
});
// 省略过长字符串详细，鼠标悬停展示全部
$yd.formatDetail = function (value) {
    if ($yd.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:purple' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:purple' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
//fileinput
$yd.fileinput = function (ele) {
    try {
        $(ele).fileinput('destroy');
    } catch (e) {
    }
    var that = this;
    this.theme = 'explorer';
    this.language = "zh";
    this.uploadAsync = false;
    this.uploadUrl = "/sysPictrue/upload";
    this.deleteUrl = "/sysPictrue/upload/delete";
    this.overwriteInitial = false;
    this.initialPreviewAsData = true;
    this.reversePreviewOrder = true;
    this.fileActionSettings = {
        showUpload: false
    };
    this.initialPreview = [];
    this.initialPreviewConfig = [];
    this.showClose = false;
    // this.showBrowse = true;
    // this.showCaption = false;
    this.onlyBtn = function () {
        this.showPreview = false;
        this.showCaption = false;
        return this;
    };
    this.setOne = function () {
        this.autoReplace = true;
        this.maxFileCount = 1;
        return this;
    };
    this.render = function (ids) {
        if (!ids) {
            _r();
        } else {
            $yd.get("/sysPictrue/ids/" + ids, function (data) {
                $.each(data, function (i, n) {
                    that.initialPreview.push($.urlPre + n['path']);
                    n.frameAttr = {'picid': n.id};
                    that.initialPreviewConfig.push(n);
                });
                _r();
            });
        }

        function _r() {
            $(ele).fileinput(that)
                .on('filebatchuploadsuccess', that.filebatchuploadsuccess)
                .on('filebatchuploadcomplete', that.filebatchuploadcomplete);
        }

        return this;
    };
    this.renderNew = function (ids) {
        if (!ids) {
            _r();
        } else {
            $yd.get("/tticar/ids/" + ids, function (data) {
                $.each(data, function (i, n) {
                    that.initialPreview.push($.urlPre + n['path']);
                    n.frameAttr = {'picid': n.id};
                    that.initialPreviewConfig.push(n);
                });
                _r();
            });
        }

        function _r() {
            $(ele).fileinput(that)
                .on('filebatchuploadsuccess', that.filebatchuploadsuccess)
                .on('filebatchuploadcomplete', that.filebatchuploadcomplete);
        }

        return this;
    };
    that.rIds = null;
    this.filebatchuploadsuccess = function (event, data) {
        that.rIds = data.response.ids;
    };
    this.filebatchuploadcomplete = function (event, files, extra) {
        if (that.rIds) {
            $(ele).fileinput('getFrames', '.file-preview-success:not([picid])').each(function (i) {
                $(this).attr('picid', that.rIds[i]);
            });
        }
        that.rIds = null;
    };
    this.getValues = function () {
        var values = [];
        $(ele).fileinput('getFrames', '.kv-preview-thumb').each(function () {
            if ($(this).attr('picid')) {
                values.push($(this).attr('picid'));
            }
        });
        return values;
    };
    return this;
};

//
$yd.post = function (url, data, fn) {
    if (typeof  data === 'function') {
        fn = data;
        data = {};
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,//将对象序列化成JSON字符串
        dataType: "json",
        contentType: typeof data === 'string' ? 'application/json;charset=utf-8' : "application/x-www-form-urlencoded",
        dataFilter: function (data, type) {
            return data;
        },
        success: function (data) {
            if (data.code == 0) {
                if (fn) {
                    fn(data['data']);
                }
            } else {
                $yd.alert(data.message, 'error');
            }
        },
        error: function (res) {
            $yd.alert(res['responseJSON']['error'], 'error');
        }
    });
};

$yd.postReceive = function (url, data, fn) {
    if (typeof  data === 'function') {
        fn = data;
        data = {};
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,//将对象序列化成JSON字符串
        dataType: "json",
        contentType: typeof data === 'string' ? 'application/json;charset=utf-8' : "application/x-www-form-urlencoded",
        dataFilter: function (data, type) {
            return data;
        },
        success: function (data) {
            if (data.code == 0) {
                if (fn) {
                    fn(data['data']);
                }
                $yd.alert('接单成功');

            } else {
                $yd.alert(data.message, 'error');
            }
        },
        error: function (res) {
            $yd.alert(res['responseJSON']['error'], 'error');
        }
    });
};

$yd.postNotReceive = function (url, data, fn) {
    if (typeof  data === 'function') {
        fn = data;
        data = {};
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,//将对象序列化成JSON字符串
        dataType: "json",
        contentType: typeof data === 'string' ? 'application/json;charset=utf-8' : "application/x-www-form-urlencoded",
        dataFilter: function (data, type) {
            return data;
        },
        success: function (data) {
            if (data.code == 0) {
                if (fn) {
                    fn(data['data']);
                }
                $yd.alert('拒绝接单成功');

            } else {
                $yd.alert(data.message, 'error');
            }
        },
        error: function (res) {
            $yd.alert(res['responseJSON']['error'], 'error');
        }
    });
};

// get
$yd.get = function (url, data, fn) {
    if (typeof  data === 'function') {
        fn = data;
        data = {};
    }
    $.get(url, data, function (data) {
        if ($.isArray(data)) {
            fn(data);
            return;
        }
        if (data.code == 0) {
            fn(data['data']);
        } else {
            $yd.alert(data.message, 'error');
        }
    });
};

$yd.confirm = function (msg, fn) {
    if (typeof msg === 'function') {
        fn = msg;
        msg = "请确认操作是否继续？";
    }
    $.messager.confirm({
        title: '确认框',
        border: false,
        top: 0,
        msg: msg,
        fn: function (r) {
            if (r) {
                fn()
            }
        }
    })
    ;
};

$yd.confirmReceive = function (msg, fn,status) {
    if (typeof msg === 'function') {
        fn = msg;
        msg = "确认接单？";
    }
    $.messager.confirm({
        title: '确认框',
        border: false,
        top: 0,
        msg: msg,
        fn: function (r) {
            if (r) {
                fn()
            }
        }
    })
    ;
};

$yd.confirmNotReceive = function (msg, fn) {
    if (typeof msg === 'function') {
        fn = msg;
        msg = "确认拒绝接单？";
    }
    $.messager.confirm({
        title: '确认框',
        border: false,
        top: 0,
        msg: msg,
        fn: function (r) {
            if (r) {
                fn()
            }
        }
    })
    ;
};
//
$yd.show = function (msg) {
    $.messager.show({
        msg: msg,
        timeout: 800,
        showType: 'fade',
        border: false,
        height: 40,
        bodyCls: 'my-message',
        style: {
            'z-index': 99999
            , top: document.body.scrollTop + document.documentElement.scrollTop,
        }
    });
};
//提醒 error,question,info,warning.
$yd.alert = function (msg, fn, icon) {
    var ops = {
        border: false,
        title: '提醒框',
        icon: icon || 'warning',
        msg: msg,
        top: 0,
        onOpen: function () {
            $yd.isForbidCutKey = 1;//禁用快捷键
        },
        onBeforeDestroy: function () {
            setTimeout("$yd.isForbidCutKey = 0", 500);//开启快捷键
        }
    };
    if (typeof fn === 'function')   ops.fn = fn;
    if (typeof fn === 'string')   ops.icon = fn;
    $.messager.alert(ops);
};

// 表单
$yd.form = function (form) {
    var that = this;
    this.load = function (data) {
        $(form).form('load', data);
        return this;
    };
    this.url = function (url) {
        this.url = url;
        return this;
    };
    this.pre = function (fn) {
        that._preSub = fn;
        return this;
    };
    this.submit = function (fn) {
        $(form).form('submit', {
            url: this.url,
            // dirty: true,
            onSubmit: function (param) {
                var isPre = false;
                if (typeof that._preSub === 'function') {
                    isPre = that._preSub(param);
                }
                return $(this).form('validate') && !isPre;
            },
            success: function (data) {
                var data = JSON.parse(data);
                if (data.code == 0) {
                    if (fn) fn(data['data'])
                } else {
                    $yd.isForbidCutKey = 1;
                    $yd.alert(data.message);
                }
            }
        });
    }
};
$yd.form.create = function (form) {
    return new $yd.form(form);
};

// 弹出窗口
$yd.win = function (title, href) {
    var that = this;
    this._win = $('<div class="my-win"></div>');
    this.buttons = [];
    this.addBtn = function (text, cls, fn) {
        this.buttons.push({
            text: text, iconCls: cls, handler: function () {
                var $this = $(this);
                $this.splitbutton('disable');
                fn(that, $(this).parent().prev());
                try {
                    $this.splitbutton('enable');
                } catch (e) {
                }
            }
        });
        return this;
    };
    this.addBtn('关闭', 'icon-clear', function (that) {
        that.close();
    });
    this.big = function () {
        this.width = '88%';
        this.height = '92%';
        this.top = '2%';
        return this;
    };
    this.close = function () {
        this._win.dialog('destroy');
    };
    this.setContent = function (content) {
        this.content = content;
        return this;
    };
    this.isFrame = function () {
        this._isFrame = true;
        return this;
    };
    this.innerEle = function (ele) {
        var $jquery = this._win.find('iframe')[0].contentWindow.$;
        return $jquery(ele);
    };
    /**
     * @param fn1 框口加载完成回调
     * @param fn2 保存按钮回调
     * @param fn3 关闭框口回调
     */
    this.open = function (fn1, fn2, fn3) {
        if (fn2) this.addBtn('保存', 'icon-ok', fn2);
        var ops = {
            title: title,
            iconCls: 'icon-save',
            maximizable: true,
            collapsible: true,
            minimizable: false,
            border: false,
            openAnimation: 'fade',
            top: this.top || '5%',
            width: this.width || '60%',
            height: this.height || '75%',
            modal: true,
            buttons: this.buttons,
            onLoad: function () {
                if (fn1) fn1(that, $(this));
            },
            onClose: function () {
                $(this).dialog('destroy');
            }
        };
        if (href) {
            if (this._isFrame) {
                ops.content = '<iframe src="' + href + '" style="border:0;height: 100%;width: 100%;">'
            } else {
                ops.href = href;
            }
        }
        if (this.content) ops.content = this.content;
        if (fn3) ops.onDestroy = fn3;
        this._win.dialog(ops);
    };
    return this;
};

$yd.win.create = function (title, href) {
    return new $yd.win(title, href);
};

$yd.win.createDelivery = function (title, href) {
    return new $yd.winDelivery(title, href);
};



// 初始化页面操作按钮
$yd.SearchBtn = function ($btn) {
    this.create = function (type, title, fn, per) {
        if (per && !$.hasPer(per)) return;
        var $a = $('<a class="bt-' + type + '"><i class="fa fa-' + type + '"></i>&nbsp;' + title + '</a>');
        $a.click(function () {
            fn();
        });
        $btn.prepend($a);
        $a.linkbutton({plain: true});
    };
    this.on = function (type, fn) {
        $btn.on(type, fn);
    };
    this.init = function () {
        var $t = $btn.closest('.layout-panel-north').find('.panel-title');
        $t.html($btn).height('auto');
        $t.find('a').linkbutton({plain: true});
        $btn.show();
    };
};

// 下拉树形表格
$yd.combotreegrid = function (ops, onlyLeafCheck) {
    var id = ops + "_toolbar";
    if ($(id).length == 0) {
        var _id = id.replace('#', '');
        $('body').append('<div id="' + _id + '"><input id="' + _id + '_s" class="easyui-searchbox" type="text"></div>');
    }
    var that = new $yd.TreeGrid(ops);
    that.toolbar = id;
    that.panelMinWidth = 340;
    that.columns = [[]];
    that.searchField = null;// 初始化查询条件
    that.addCol = function (field, title) {
        if (that.searchField == null) {
            that.searchField = field;
            $(id + '_s').searchbox({
                searcher: function (value, name) {
                    var param = {};
                    param[field] = value;
                    $(ops).combotreegrid('grid').treegrid('reload', param);
                },
                prompt: title + '模糊匹配'
            });
        }
        that.columns[0].push({field: field, title: title, width: 50});
        return that;
    };
    that.load = function (url) {
        that.url = url;
        $(ops).combotreegrid(this);
        return that;
    };
    that.onBeforeSelect = function (node) {
        if(onlyLeafCheck != undefined && onlyLeafCheck == true) {
            if(node.category_type !=3){
                var tree = $(this).tree;
                tree('unselect',node.target);
            } else {
                return true;
            }
        }
        return true;
    };

    return that;
};

// 下拉表格
$yd.combogrid = function (ops, func) {
    var id = ops + "_toolbar";
    if ($(id).length == 0) {
        var _id = id.replace('#', '');
        $('body').append('<div id="' + _id + '"><input id="' + _id + '_s" class="easyui-searchbox" type="text"></div>');
    }
    var that = new $yd.DataGrid(ops);
    that.toolbar = id;
    that.panelMinWidth = 340;
    that.columns = [[]];
    that.searchField = null;// 初始化查询条件
    that.addCol = function (field, title, ext) {
        if (that.searchField == null) {
            that.searchField = field;
            $(id + '_s').searchbox({
                searcher: function (value, name) {
                    var param = {};
                    param[field] = value;
                    $(ops).combogrid('grid').datagrid('reload', param);
                },
                prompt: title + '模糊匹配'
            });
        }
        var _c = {field: field, title: title, width: 50};
        if (ext) $.extend(_c, ext);
        that.columns[0].push(_c);
        return that;
    };
    that.addCheckbox = function (field) {
        that.idField = field;
        var _c = {field: id, checkbox: true};
        that.columns[0].push(_c);
        return that;
    };
    that.load = function (url) {
        that.url = url;
        $(ops).combogrid(this);
    };
    that.onChange = function (a,b) {
        var g = $(ops).combogrid('grid');	// get datagrid object
        var r = g.datagrid('getSelected');	// get the selected row
        if(func) {
            func(r);
        }
    };
    return that;
};

//树形表格
$yd.TreeGrid = function (ops) {
    var that = new $yd.DataGrid1();
    that.treeField = 'name';
    that.loadFilter = function (data) {
        if (this.isChild) return data.records;
        data.rows = data.records;
        return data;
    };
    that.onBeforeLoad = function (row, param) {
        param.id = param.id || 0;
        if (param.id != 0) {
            this.isChild = true;
            param.page = 1;
            param.rows = 100;
        }
    };
    that.loadGrid = function () {
        $(ops).treegrid(this);
    };
    return that;
};

// 数据表格
$yd.DataGrid = function (ops) {
    this.method = 'get';
    this.pagination = true;
    this.singleSelect = false;
    this.fit = true;
    this.border = false;
    this.loadMsg = '加载中...';
    this.fitColumns = true;
    this.autoRowHeight = false;
    this.ctrlSelect = false;
    this.pageSize = 20;
    this.pageList = [10, 20, 50, 100, 500];
    this.idField = 'id';
    this.textField = 'name';
    this.onLoadSuccess = function () {
        // $(this).datagrid('enableDnd');
    };
    this.loadFilter = function (data) {
        data.rows = data.records;
        return data;
    };
    this.loadGrid = function () {
        $(ops).datagrid(this);
    }
};
$yd.DataGrid1 = function (ops) {
    this.method = 'get';
    this.pagination = true;
    this.singleSelect = true;
    this.fit = true;
    this.border = false;
    this.loadMsg = '加载中...';
    this.fitColumns = true;
    this.autoRowHeight = false;
    this.ctrlSelect = false;
    this.pageSize = 20;
    this.pageList = [10, 20, 50, 100, 500];
    this.idField = 'id';
    this.textField = 'name';
    this.onLoadSuccess = function () {
        // $(this).datagrid('enableDnd');
    };
    this.loadFilter = function (data) {
        data.rows = data.records;
        return data;
    };
    this.loadGrid = function () {
        $(ops).datagrid(this);
    }
};

$yd.combobox = function (ele) {
    if (typeof ele === 'string')  ele = $('#' + ele);
    this.required = true;
    this.multiple = false; // true为多选
    this.editable = false;
    this.panelHeight = 'auto';
    this.valueField = 'id';
    this.textField = 'name';
    this.method = 'get';
    this.load = function (url) {
        this.url = url;
        ele.combobox(this);
        return this;
    };
    this.setValue = function (value) {
        if (value) ele.combobox('setValue', value);
    }
};
//非必填
$yd.comboboxFalse = function (ele) {
    if (typeof ele === 'string')  ele = $('#' + ele);
    this.required = false;
    this.multiple = false;
    this.editable = false;
    this.panelHeight = 'auto';
    this.valueField = 'id';
    this.textField = 'name';
    this.method = 'get';
    this.load = function (url) {
        this.url = url;
        ele.combobox(this);
        return this;
    };
    this.setValue = function (value) {
        if (value) ele.combobox('setValue', value);
    }
};

// 下拉
$yd.combo = function () {
    this.required = true;
    this.multiple = false;
    this.editable = false;
    this.panelHeight = 'auto';
};

// 绑定enter事件
$yd.bindEnter = function (fn) {
    var $form = $('form.search-form');
    if ($form.length) {
        $form.keyup(function (event) {
            if (event.keyCode == 13) {
                fn();
            }
        });
    }
};

//数据表格
$yd.datalist = function (ele) {
    this.method = 'get';
    this.checkbox = true;
    this.lines = true;
    this.singleSelect = false;
    this.valueField = 'id';
    this.textField = 'name';
    this.idField = 'id';
    this.load = function (url) {
        this.url = url;
        $(ele).datalist(this);
    };
};

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
// 编辑器的动态添加和移除
$.extend($.fn.datagrid.methods, {
    addEditor : function(jq, param) {
        if (param instanceof Array) {
            $.each(param, function(index, item) {
                var e = $(jq).datagrid('getColumnOption', item.field);
                e.editor = item.editor;
            });
        } else {
            //获取datagrid字段的属性
            var e = $(jq).datagrid('getColumnOption', param.field);
            //给编辑器赋值
            e.editor = param.editor;
        }
    },
    removeEditor : function(jq, param) {
        if (param instanceof Array) {
            $.each(param, function(index, item) {
                var e = $(jq).datagrid('getColumnOption', item);
                e.editor = {};
            });
        } else {
            var e = $(jq).datagrid('getColumnOption', param);
            e.editor = {};
        }
    }
});


// 图片详情处理
$yd.picDesc = function (ops) {
    var $ul = $(ops).find('ul.pic-desc'), $li = $ul.find('li'), $cli = $li.clone();
    $ul.unbind().sortable({
        revert: true,
        forceHelperSize: true,
        forcePlaceholderSize: true
    });
    $li.remove();
//
    $(ops).unbind().on('click', 'a.text', function () {
        var _cli = $cli.clone(), $content = _cli.find('.content');
        _cli.data("type", 'text');
        text($content, _cli);
        $ul.append(_cli);
    }).on('click', 'a.image', function () {
        picture(function (path) {
            var _cli = $cli.clone(), $content = _cli.find('.content');
            _cli.data("type", 'image').data("value", path);
            $content.html($('<img src="' + path + '" style="width: 100%;">'));
            $ul.append(_cli);
        });
    }).on('click', 'a.video', function () {
    }).on('click', 'a.panel-tool-close', function () {
        $(this).closest('li').remove();
    }).on('click', 'a.icon-edit', function () {
        var $this = $(this).closest('li'), type = $this.data('type'), $content = $this.find('.content');
        switch (type) {
            case 'text':
                text($content, $this);
                break;
            case 'image':
                picture(function (path) {
                    $content.html($('<img src="' + path + '" style="width: 100%;">'));
                    $this.data('value', path);
                });
                break;
        }
    });

    this.setValue = function (values) {
        try {
            values = JSON.parse(values);
        } catch (e) {
            values = [];
        }
        $ul.html('');
        $.each(values, function (i, n) {
            var _cli = $cli.clone(), $content = _cli.find('.content');
            _cli.data('type', n['type']).data('value', n['value']);
            switch (n['type']) {
                case 'text':
                    $content.text(n['value']);
                    break;
                case 'image':
                    $content.html($('<img src="' + n['value'] + '" style="width: 100%;">'));
                    break;
            }
            $ul.append(_cli);
        })
    };
    this.getValue = function () {
        var lis = [];
        $ul.find('li').each(function () {
            lis.push({type: $(this).data('type'), value: $(this).data('value')});
        });
        return JSON.stringify(lis);
    };

    function picture(fn) {
        $yd.win.create("图片资源", "/sysPictrue?from=win").big().isFrame().open(null, function (that, $win) {
            var sels = that.innerEle('#picture_table').datagrid('getSelections');
            $.each(sels, function (i, n) {
                fn($.urlPre + n.path);
            });
            that.close();
        });
    }

    function text($content, _cli) {
        var editor = '<input id="_tb" class="easyui-textbox" data-options="multiline:true" value="' + $.trim($content.text()) + '" style="height:100%;width: 100%;">';
        new $yd.win.create("编辑内容").setContent(editor).open(null, function (that, $win) {
            $content.text($win.find('#_tb').textbox('getValue'));
            _cli.data('value', $win.find('#_tb').textbox('getValue'));
            that.close();
        });
    }

    return this;
};



// 弹出窗口
$yd.winNew = function (title, href) {
    var that = this;
    this._win = $('<div class="my-win"></div>');
    this.buttons = [];
    this.addBtn = function (text, cls, fn) {
        this.buttons.push({
            text: text, iconCls: cls, handler: function () {
                var $this = $(this);
                $this.splitbutton('disable');
                fn(that, $(this).parent().prev());
                try {
                    $this.splitbutton('enable');
                } catch (e) {
                }
            }
        });
        return this;
    };
    this.addBtn('保存(Enter)', 'icon-save', function (that,$win) {
        $yd.form.create($win.find('form')).url(MCateogry.u).submit(function () {
            that.close();
            MCateogry.refresh();
        });
    });
    this.big = function () {
        this.width = '88%';
        this.height = '92%';
        this.top = '2%';
        return this;
    };
    this.close = function () {
        this._win.dialog('destroy');
    };
    this.setContent = function (content) {
        this.content = content;
        return this;
    };
    this.isFrame = function () {
        this._isFrame = true;
        return this;
    };
    this.innerEle = function (ele) {
        var $jquery = this._win.find('iframe')[0].contentWindow.$;
        return $jquery(ele);
    };
    /**
     * @param fn1 框口加载完成回调
     * @param fn2 保存按钮回调
     * @param fn3 关闭框口回调
     */
    this.open = function (fn1, fn2, fn3) {
        if (fn2) this.addBtn('保存并继续新增(Ctrl+Enter)', 'icon-add', fn2);
        var ops = {
            title: title,
            iconCls: 'icon-save',
            maximizable: true,
            collapsible: true,
            minimizable: false,
            border: false,
            openAnimation: 'fade',
            top: this.top || '5%',
            width: this.width || '60%',
            height: this.height || '75%',
            modal: true,
            buttons: this.buttons,
            onLoad: function () {
                if (fn1) fn1(that, $(this));
            },
            onClose: function () {
                $(this).dialog('destroy');
            }
        };
        if (href) {
            if (this._isFrame) {
                ops.content = '<iframe src="' + href + '" style="border:0;height: 100%;width: 100%;">'
            } else {
                ops.href = href;
            }
        }
        if (this.content) ops.content = this.content;
        if (fn3) ops.onDestroy = fn3;
        this._win.dialog(ops);
    };
    return this;
};

$yd.win.createNew = function (title, href) {
    return new $yd.winNew(title, href);
};

// 弹出窗口
$yd.win2 = function (title, href) {
    var that = this;
    this._win = $('<div class="my-win"></div>');
    this.buttons = [];
    this.addBtn = function (text, cls, fn) {
        this.buttons.push({
            text: text, iconCls: cls, handler: function () {
                var $this = $(this);
                $this.splitbutton('disable');
                fn(that, $(this).parent().prev());
                try {
                    $this.splitbutton('enable');
                } catch (e) {
                }
            }
        });
        return this;
    };
    // this.addBtn('关闭', 'icon-clear', function (that) {
    //     that.close();
    // });
    this.big = function () {
        this.width = '88%';
        this.height = '92%';
        this.top = '2%';
        return this;
    };
    this.close = function () {
        this._win.dialog('destroy');
    };
    this.setContent = function (content) {
        this.content = content;
        return this;
    };
    this.isFrame = function () {
        this._isFrame = true;
        return this;
    };
    this.innerEle = function (ele) {
        var $jquery = this._win.find('iframe')[0].contentWindow.$;
        return $jquery(ele);
    };
    /**
     * @param fn1 框口加载完成回调
     * @param fn2 保存按钮回调
     * @param fn3 关闭框口回调
     * @param fn4 保存并继续回调
     */
    this.open = function (fn1, fn2, fn3, fn4) {
        if (fn2) this.addBtn('保存(Enter)', 'icon-save', fn2);
        if (fn4) this.addBtn('保存并继续新增(Ctrl+Enter)', 'icon-add', fn4);
        var ops = {
            title: title,
            iconCls: 'icon-save',
            maximizable: true,
            collapsible: true,
            minimizable: false,
            border: false,
            openAnimation: 'fade',
            top: this.top || '5%',
            width: this.width || '60%',
            height: this.height || '75%',
            modal: true,
            buttons: this.buttons,
            onLoad: function () {
                if (fn1) fn1(that, $(this));
            },
            onClose: function () {
                $(this).dialog('destroy');
            }
        };
        if (href) {
            if (this._isFrame) {
                ops.content = '<iframe src="' + href + '" style="border:0;height: 100%;width: 100%;">'
            } else {
                ops.href = href;
            }
        }
        if (this.content) ops.content = this.content;
        if (fn3) ops.onDestroy = fn3;
        this._win.dialog(ops);
    };
    return this;
};

$yd.win2.create = function (title, href) {
    return new $yd.win2(title, href);
};



// 弹出窗口
$yd.win3 = function (title, href) {
    var that = this;
    this._win = $('<div class="my-win"></div>');
    this.buttons = [];
    this.addBtn = function (text, cls, fn) {
        this.buttons.push({
            text: text, iconCls: cls, handler: function () {
                var $this = $(this);
                $this.splitbutton('disable');
                fn(that, $(this).parent().prev());
                try {
                    $this.splitbutton('enable');
                } catch (e) {
                }
            }
        });
        return this;
    };
    // this.addBtn('关闭', 'icon-clear', function (that) {
    //     that.close();
    // });
    this.big = function () {
        this.width = '88%';
        this.height = '92%';
        this.top = '2%';
        return this;
    };
    this.close = function () {
        this._win.dialog('destroy');
    };
    this.setContent = function (content) {
        this.content = content;
        return this;
    };
    this.isFrame = function () {
        this._isFrame = true;
        return this;
    };
    this.innerEle = function (ele) {
        var $jquery = this._win.find('iframe')[0].contentWindow.$;
        return $jquery(ele);
    };
    /**
     * @param fn1 框口加载完成回调
     * @param fn2 保存按钮回调
     * @param fn3 关闭框口回调
     * @param fn4 保存并继续回调
     */
    this.open = function (fn1, fn2, fn3, fn4) {
        if (fn2) this.addBtn('确认', 'icon-save', fn2);
        if (fn4) this.addBtn('保存并继续新增(Ctrl+Enter)', 'icon-add', fn4);
        var ops = {
            title: title,
            iconCls: 'icon-save',
            maximizable: true,
            collapsible: true,
            minimizable: false,
            border: false,
            openAnimation: 'fade',
            top: this.top || '5%',
            width: this.width || '60%',
            height: this.height || '75%',
            modal: true,
            buttons: this.buttons,
            onLoad: function () {
                if (fn1) fn1(that, $(this));
            },
            onClose: function () {
                $(this).dialog('destroy');
            }
        };
        if (href) {
            if (this._isFrame) {
                ops.content = '<iframe src="' + href + '" style="border:0;height: 100%;width: 100%;">'
            } else {
                ops.href = href;
            }
        }
        if (this.content) ops.content = this.content;
        if (fn3) ops.onDestroy = fn3;
        this._win.dialog(ops);
    };
    return this;
};

$yd.win3.create = function (title, href) {
    return new $yd.win3(title, href);
};

// 弹出窗口
$yd.winDelivery = function (title, href) {
    var that = this;
    this._win = $('<div class="my-win"></div>');
    this.buttons = [];
    this.addBtn = function (text, cls, fn) {
        this.buttons.push({
            text: text, iconCls: cls, handler: function () {
                var $this = $(this);
                $this.splitbutton('disable');
                fn(that, $(this).parent().prev());
                try {
                    $this.splitbutton('enable');
                } catch (e) {
                }
            }
        });
        return this;
    };
    this.addBtn('关闭', 'icon-clear', function (that) {
        that.close();
    });
    this.big = function () {
        this.width = '88%';
        this.height = '92%';
        this.top = '2%';
        return this;
    };
    this.close = function () {
        this._win.dialog('destroy');
    };
    this.setContent = function (content) {
        this.content = content;
        return this;
    };
    this.isFrame = function () {
        this._isFrame = true;
        return this;
    };
    this.innerEle = function (ele) {
        var $jquery = this._win.find('iframe')[0].contentWindow.$;
        return $jquery(ele);
    };
    /**
     * @param fn1 框口加载完成回调
     * @param fn2 保存按钮回调
     * @param fn3 关闭框口回调
     */
    this.open = function (fn1, fn2, fn3) {
        if (fn2) this.addBtn('确认发货', 'icon-ok', fn2);
        var ops = {
            title: title,
            iconCls: 'icon-save',
            maximizable: true,
            collapsible: true,
            minimizable: false,
            border: false,
            openAnimation: 'fade',
            top: this.top || '5%',
            width: this.width || '60%',
            height: this.height || '75%',
            modal: true,
            buttons: this.buttons,
            onLoad: function () {
                if (fn1) fn1(that, $(this));
            },
            onClose: function () {
                $(this).dialog('destroy');
            }
        };
        if (href) {
            if (this._isFrame) {
                ops.content = '<iframe src="' + href + '" style="border:0;height: 100%;width: 100%;">'
            } else {
                ops.href = href;
            }
        }
        if (this.content) ops.content = this.content;
        if (fn3) ops.onDestroy = fn3;
        this._win.dialog(ops);
    };
    return this;
};
// 全局ajax配置
$.ajaxSetup({
    // dataType: "JSON",
    // contentType: "application/json",
    // contentType: "application/x-www-form-urlencoded;charset=utf-8",
    cache: false,
    complete: function (XMLHttpRequest) {
        //token过期，则跳转到登录页面
        var httpStatus=XMLHttpRequest.status;
        if(httpStatus==200 && "parsererror" ==XMLHttpRequest.statusText && XMLHttpRequest.responseText.match("库存管理软件登录")){
            //如果超时就处理 ，指定要跳转的页面(比如登陆页)
            window.location.replace("/login");
        }
    }
});

